package com.studyweb.config;

import com.studyweb.utils.FileUploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * 文件访问配置类
 * 
 * <p>配置静态资源访问路径，使上传的文件可以通过URL直接访问</p>
 * 
 * @author StudyWeb Team
 * @since 1.0.0
 */
@Slf4j
@Configuration
public class FileAccessConfig implements WebMvcConfigurer {
    
    @Autowired
    private FileUploadProperties fileUploadProperties;
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 获取文件上传路径和URL前缀
        String uploadPath = fileUploadProperties.getPath();
        String urlPrefix = fileUploadProperties.getUrlPrefix();
        
        // 确保路径以斜杠结尾
        if (!uploadPath.endsWith("/") && !uploadPath.endsWith("\\")) {
            uploadPath += File.separator;
        }
        
        if (!urlPrefix.endsWith("/")) {
            urlPrefix += "/";
        }
        
        // 配置静态资源映射，禁用缓存以确保文件删除即时生效
        registry.addResourceHandler(urlPrefix + "**")
                .addResourceLocations("file:" + uploadPath)
                .setCacheControl(CacheControl.noCache().noStore().mustRevalidate()) // 禁用所有缓存
                .resourceChain(false); // 禁用资源链
        
        log.info("文件访问配置完成 - URL前缀: {}, 物理路径: {}", urlPrefix, uploadPath);
        
        // 创建上传目录（如果不存在）
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (created) {
                log.info("创建上传目录成功: {}", uploadPath);
            } else {
                log.error("创建上传目录失败: {}", uploadPath);
            }
        }
    }
}